package com.GamersCom.games;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.GamersCom.db.Game;
import com.GamersCom.db.Genre;
import com.GamersCom.db.Platform;
import com.GamersCom.model.GameMgr;
import com.GamersCom.model.GenreMgr;
import com.GamersCom.model.MgrFactory;
import com.GamersCom.model.PlatformMgr;

/**
 * Servlet implementation class NewGame
 */
public class NewGame extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		String nextView = "/newGameForm.jsp";
		MgrFactory factory = (MgrFactory) this.getServletContext()
				.getAttribute("mgrFactory");
		PlatformMgr pfMgr = factory.getPlatformMgr();
		GenreMgr genreMgr = factory.getGenreMgr();
		GameMgr gameMgr = factory.getGameMgr();

		// retrieve the parameter
		try
		{
			List<Platform> pfList = pfMgr.getAll();
			List<Genre> genreList = genreMgr.getAll();
			request.setAttribute("pfList", pfList);
			request.setAttribute("genreList", genreList);
		}
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		request.getRequestDispatcher(nextView).forward(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession session = request.getSession();
		String nextView = "/newGameForm.jsp";
		String name = request.getParameter("name");
		String company = request.getParameter("company");
		String website = request.getParameter("website");
		String release = request.getParameter("releaseDate");
		String summary = request.getParameter("summary");
		// String platform = request.getParameter("platform");
		// String genre = request.getParameter("genre");
		String platform = request.getParameter("platform");
		String genre = request.getParameter("genre");
		MgrFactory factory = (MgrFactory) this.getServletContext()
				.getAttribute("mgrFactory");
		GameMgr gameMgr = factory.getGameMgr();

		Game game = new Game();
		game.setName(name);
		game.setCompany(company);
		game.setWebsite(website);
		game.setSummary(summary);
		game.setPlatform(platform);
		game.setGenre(genre);

		try
		{
			gameMgr.insert(game);
			request.setAttribute("msg", "Add successfully!");
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}

		request.getRequestDispatcher(nextView).forward(request, response);
	}

}
